import os
import subprocess
import re
import pyautogui
import tr
from PIL import Image
import pytesseract
import tkinter

def click_enter(num):
    inputs=[]
    for i in range(num):
        inputs.append('enter')
    pyautogui.typewrite(inputs,1)

def getFenbianlv():
    screen=tkinter.Tk()
    x,y=screen.winfo_screenwidth(),screen.winfo_screenheight()
    screen.destroy()
    return x,y
def trip(text):
    text=text.replace(" ","") 
    text=text.replace("\n","")
    return text
def get_active_window_rect():
        result = subprocess.run('xdotool getwindowfocus getwindowgeometry', shell=True, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        s = result.stdout.decode('utf-8')
        print(s)
        res = re.findall("Position: (\d+)?,(\d+)? \(.*", s)
        if len(res) == 0:
            return 0,0,0,0
        x, y = list(map(int, res[0]))
        res = re.findall("Geometry: (\d+)?x(\d+)?", s)
        if len(res) == 0:
            return 0,0,0,0
        w, h = list(map(int, res[0]))
        return x, y-70, w, h+20

def screenshot(point,path,senseSize):
    w,h=point[2],point[3]
    w_max,h_max=getFenbianlv()
    # judge the windows is not useful
    if senseSize:
        if w_max*h_max/(w*h)>18:
            point=(0,0,w_max,h_max)
    im=pyautogui.screenshot(region=point)
    im.save(path)


def ocrImage(path):
    res= pytesseract.image_to_string(Image.open(path))
    res=res.lower()
    return trip(res)

def click(x,y):
    pyautogui.moveTo(x, y)
    pyautogui.click()

def mkdirIfNotExits(dirs):
    if not os.path.exists(dirs):
        os.makedirs(dirs)

def touchIfNotExits(file):
    if not os.path.exists(file):
        os.system(r"touch {}".format(file))


def getContent(title,body):
    msg="###############################"+str(title)+"#############################################"+"\n"+str(body)+"\n"
    return msg



def ocrImageChinese(path):
   # res= pytesseract.image_to_string(Image.open(path),lang='chi_sim')
   # print(res.encode("utf-8").decode("utf-8"))
   # return trip(res)
  
   arrs=tr.run(path)
   res=""
   for each in arrs:
       
       res+=each[1]
  # print(res)
   return trip(res)

def  levenshtein_distance(first , second):
    if  len(first) ==  0  or  len(second) ==  0:
        return  len(first) +  len(second)
    first_length =  len(first) +  1
    second_length =  len(second) +  1
    distance_matrix = [ list(range(second_length))  for  i  in list(range(first_length))]  # 初始化矩阵
    for i  in  range( 1 , first_length):
        for j  in  range( 1 , second_length):
            deletion = distance_matrix[i- 1][j] +  1
            insertion = distance_matrix[i][j- 1] +  1
            substitution = distance_matrix[i- 1][j- 1]
            if first[i- 1] != second[j- 1]:
                substitution +=  1
            distance_matrix[i][j] =  min(insertion , deletion , substitution)
    return distance_matrix[first_length- 1][second_length- 1]

